package com.wh.wisdomsite.xbox.core;


import com.wh.wisdomsite.xbox.core.impl.DefaultXboxRequestContext;
import com.wh.wisdomsite.xbox.common.ServiceMethodHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.InvocationTargetException;


/**
 * 通过该服务方法适配器调用目标的服务方法
 * User: yl
 * Date: 13-1-28
 * Time: 下午12:02
 */
public class ServiceMethodAdapter {


    private static final Log logger = LogFactory.getLog(ServiceMethodAdapter.class);

    /**
     * 调用服务方法
     * @param context
     * @return
     */
    public Object invokeServiceMethod(DefaultXboxRequestContext context) {
        ServiceMethodHandler serviceMethodHandler = null;
        try {
            serviceMethodHandler = context.getServiceMethodHandler();
            logger.info("调用服务方法：" + serviceMethodHandler.getHandler().getClass() + "." + serviceMethodHandler.getMethod().getName());
            if (serviceMethodHandler.isHandlerMethodWithParameter()) {
                return serviceMethodHandler.getMethod().invoke(serviceMethodHandler.getHandler(), context.getXboxRequest());
            } else {
                return serviceMethodHandler.getMethod().invoke(serviceMethodHandler.getHandler());
            }
        } catch (Throwable e) {
            if(null != serviceMethodHandler){
              logger.error("调用服务方法：" + serviceMethodHandler.getHandler().getClass() + "." + serviceMethodHandler.getMethod().getName() + " 错误原因:", e);
            }
            if (e instanceof InvocationTargetException) {
                InvocationTargetException invocationTargetException = (InvocationTargetException) e;
                throw new RuntimeException(invocationTargetException.getTargetException());
            } else {
                throw new RuntimeException(e);
            }
        }
    }
}
